package com.neusoft.dao.impl;

import com.neusoft.dao.TeachersDao;
import com.neusoft.pojo.*;
import com.neusoft.utils.DBUtil;

import java.util.ArrayList;
import java.util.List;
import java.sql.*;
public class TeachersDaoImpl implements TeachersDao {
    @Override
    public List<Teacher> findAll() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Teacher> list = new ArrayList<>();
        Classes classes = null;
        Teacher teacher = null;
        Student student = null;
        Score score = null;
        Course course = null;

        try {
            conn = DBUtil.getConn();
            pstmt = conn.prepareStatement("SELECT t.teacher_name,c.class_name,s.student_name,co.course_name,sc.grade\n" +
                    "FROM teacher t JOIN classes c ON t.class_id=c.class_id\n" +
                    "JOIN student s ON c.class_id=s.class_id\n" +
                    "JOIN score sc ON s.student_id = sc.student_id\n" +
                    "JOIN course co ON sc.course_id=sc.course_id");
            rs = pstmt.executeQuery();
            while(rs.next()){
                teacher = new Teacher();
                teacher.setTeahcer_name(rs.getString("teacher_name"));
                classes = new Classes();
                classes.setClass_name(rs.getString("class_name"));
                student = new Student();
                student.setStudent_name(rs.getString("student_name"));
                course = new Course();
                course.setCourse_name(rs.getString("course_name"));
                score = new Score();
                score.setGrade(rs.getInt("grade"));

                teacher.setClasses(classes);
                classes.setStudent(student);
                student.setScore(score);
                score.setCourse(course);
                list.add(teacher);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.closeAll(rs,pstmt,conn);
        }
        return list;
    }
}
